package mobi.daogu.powerstripcontroller

import android.content.Intent
import android.os.Bundle
import android.widget.TextView
import androidx.activity.ComponentActivity
import mobi.daogu.powerstripcontroller.remote.RemoteServer
import mobi.daogu.powerstripcontroller.widget.ConfigItemView
import java.util.LinkedList

class MainActivity : ComponentActivity() {
    private val server = RemoteServer(this::debugPrintln)
    private val debugLines = LinkedList<String>()
    private val items = ArrayList<ConfigItemView>(6)
    private val presenter = PwControlPresenter(server, items)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.main_layout)
        items.add(findViewById(R.id.item_1))
        items.add(findViewById(R.id.item_2))
        items.add(findViewById(R.id.item_3))
        items.add(findViewById(R.id.item_4))
        items.add(findViewById(R.id.item_5))
        items.add(findViewById(R.id.item_6))
        items.forEach {
            it.setOnClickListener { state ->
                startActivityForResult(Intent(this, EditorActivity::class.java).apply {
                    putExtra("index", items.indexOf(it))
                }, 123)
            }
        }
    }

    override fun onActivityReenter(resultCode: Int, data: Intent?) {
        super.onActivityReenter(resultCode, data)
        if (resultCode == 123) {
             data?.getIntExtra("index", -1)?.let { index ->
                 presenter.notifyItemUpdate(index)
             }
        }
    }

    override fun onStart() {
        super.onStart()
        server.startSync()
    }

    override fun onStop() {
        super.onStop()
        server.pauseSync()
    }

    override fun onDestroy() {
        super.onDestroy()
        server.stop()
    }

    private fun debugPrintln(line: String) {
        runOnUiThread {
            debugLines.add(line)
            if (debugLines.size > 30) {
                debugLines.removeFirst()
            }
            findViewById<TextView>(R.id.tv_debug).text = debugLines.joinToString("\n")
        }
    }
}